package com.mondo.financialwallet.presentation.ui.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.common.ui.BaseActivity;
import com.example.common.utils.TimeCount;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MobilePrefixEntity;
import com.mondo.financialwallet.data.params.SendMessageParams;
import com.mondo.financialwallet.presentation.event.LogOutEvent;
import com.mondo.financialwallet.presentation.ui.window.AreaSelectionPopupWindow;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.Toasts;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 绑定新手机号码
 */
public class BindNewMobileNumberActivity extends BaseActivity implements AreaSelectionPopupWindow.OnClickListener {

    @Order(1)
    @Bind(R.id.mobile_number_edit)
    @NotEmpty(messageResId = R.string.message_please_input_account)
    EditText mMobileNumberEdit;

    @Order(2)
    @Bind(R.id.auth_code_edit)
    @NotEmpty(messageResId = R.string.message_please_auth_code)
    EditText mAuthCodeEditText;

    @Bind(R.id.sure_button) View mSureButton;
    @Bind(R.id.area_select_layout) View mAreaSelectLayout;
    @Bind(R.id.area_select_anchor_view) View mAreaSelectAnchorView;
    @Bind(R.id.area_number_text) TextView mAreaNumberTextView;
    @Bind(R.id.send_verification_code) TextView mSendVerificationCode;


    private ProgressDialog mProgressDialog;
    private AreaSelectionPopupWindow mAreaSelectionPopupWindow;
    private Validator.ValidationListener mBindNewMobileValidationListener =
            new Validator.ValidationListener() {

                @Override
                public void onValidationSucceeded() {
                    requestBindMobileNumber();
                }

                @Override
                public void onValidationFailed(List<ValidationError> errors) {
                    if (!errors.isEmpty()) {
                        Toasts.warning(errors.get(0).getCollatedErrorMessage(
                                BindNewMobileNumberActivity.this));
                    }
                }
            };

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int getBackgroundColor() {
        return Color.WHITE;
    }

    @Override
    protected void setStatusBar() {
        ActivityTitleBarHelper.setWhiteDarkColorStatus(this);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_bind_new_mobile_number;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_bind_new_mobile_number);

        // 显示区号
        mAreaSelectLayout.setOnClickListener(v -> {
            if (mAreaSelectionPopupWindow != null) {
                mAreaSelectionPopupWindow.show(mAreaSelectAnchorView);
            }
        });

        // 发送验证码
        mSendVerificationCode.setOnClickListener(v -> requestMessageCode());

        // 绑定新手机
        Validator validator = new Validator(this);
        validator.setValidationListener(mBindNewMobileValidationListener);
        mSureButton.setOnClickListener(v -> validator.validate());

        // 手机区号
        requestMobileArea();
    }

    private void requestMobileArea() {
        DataRepository.get().mobilePrefix(result -> {
            if (result.isSuccess()) {
                List<MobilePrefixEntity.DataBean> list = result.getData();
                List<AreaSelectionPopupWindow.Area> areaList = new ArrayList<>();
                for (MobilePrefixEntity.DataBean dataBean : list) {
                    AreaSelectionPopupWindow.Area area = new AreaSelectionPopupWindow.Area(
                            dataBean.getEn_name(), dataBean.getMobile_prefix());
                    areaList.add(area);
                }

                if (mAreaSelectionPopupWindow == null) {
                    mAreaSelectionPopupWindow = new AreaSelectionPopupWindow(this, areaList);
                    mAreaSelectionPopupWindow.setOnClickListener(this);
                }
            }
        });
    }

    private void requestMessageCode() {
        String account = mMobileNumberEdit.getText().toString();
        if (TextUtils.isEmpty(account)) {
            Toasts.warning(R.string.message_please_input_account);
            return;
        }

        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(this, null,
                    getString(R.string.message_sending_sms_verification_code));

            DataRepository.get().sendMessageCode(
                    new SendMessageParams(mMobileNumberEdit.getText().toString()),
                    result -> {
                        mProgressDialog.dismiss();
                        mProgressDialog = null;

                        if (result.isSuccess()) {
                            new TimeCount(mSendVerificationCode).start();
                        } else {
                            Toasts.failure(result.getMsg());
                        }
                    }
            );
        }
    }

    private void requestBindMobileNumber() {
        String mobileNumber = mMobileNumberEdit.getText().toString();
        String code = mAuthCodeEditText.getText().toString();
        String area = mAreaNumberTextView.getText().toString();
        DataRepository.get().bindNewMobileNumber(mobileNumber, code, area, result -> {
            if (result.isSuccess()) {
                Toasts.success(R.string.message_alter_success);
                EventBus.getDefault().post(new LogOutEvent());
            } else {
                Toasts.failure(result.getMsg());
            }
        });
    }

    @Override
    public void onClick(String text) {
        mAreaNumberTextView.setText(text);
    }

    @Subscribe
    public void logoutEvent(LogOutEvent event) {
        finish();
    }
}
